package com.hello.system.controller.app;

import java.math.BigDecimal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.transaction.annotation.Transactional;
import com.hello.common.core.web.controller.BaseController;
import com.hello.common.core.web.domain.AjaxResult;
import com.hello.common.security.utils.SecurityUtils;
import com.hello.system.domain.SysUser;
import com.hello.system.domain.RentalMemberInfo;
import com.hello.system.service.ISysUserService;
import com.hello.system.service.IRentalMemberInfoService;
import lombok.RequiredArgsConstructor;

/**
 * App端用户信息接口
 * 
 * @author hello
 */
@RestController
@RequestMapping("/app/user")
@RequiredArgsConstructor
public class AppUserController extends BaseController
{
    private final ISysUserService userService;

    private final IRentalMemberInfoService rentalMemberInfoService;

    /**
     * 根据token获取我的用户信息（App端专用）
     * 
     * @return 当前登录用户信息
     */
    @GetMapping("/profile")
    public AjaxResult getProfile()
    {
        Long userId = SecurityUtils.getUserId();
        System.out.println("======== 获取用户资料请求 ========");
        System.out.println("用户ID: " + userId);
        
        SysUser originalUser = userService.selectUserById(userId);
        System.out.println("查询到的用户信息: " + (originalUser != null ? originalUser.getUserName() : "null"));
        
        if (originalUser == null) {
            System.out.println("错误: 用户信息不存在");
            return AjaxResult.error("用户信息不存在");
        }
        
        // 创建一个新的用户对象，只复制App端需要的字段
        SysUser user = new SysUser();
        user.setUserId(originalUser.getUserId());
        user.setUserName(originalUser.getUserName());
        user.setNickName(originalUser.getNickName());
        user.setEmail(originalUser.getEmail());
        user.setPhonenumber(originalUser.getPhonenumber());
        user.setSex(originalUser.getSex());
        user.setAvatar(originalUser.getAvatar());
        user.setStatus(originalUser.getStatus());
        user.setLoginIp(originalUser.getLoginIp());
        user.setLoginDate(originalUser.getLoginDate());
        user.setUserType(originalUser.getUserType());
        
        // 查询会员信息
        RentalMemberInfo memberInfo = rentalMemberInfoService.selectRentalMemberInfoByUserId(userId);
        if (memberInfo != null) {
            System.out.println("查询到的会员信息 - ID: " + memberInfo.getMemberId() + 
                             ", 钱包余额: " + memberInfo.getWalletBalance() + 
                             ", 押金余额: " + memberInfo.getDepositBalance());
        } else {
            System.out.println("未查询到会员信息");
        }
        
        // 构建data数据
        java.util.Map<String, Object> data = new java.util.HashMap<>();
        data.put("user", user);
        data.put("memberInfo", memberInfo);
        
        System.out.println("======== 获取用户资料完成 ========");
        return AjaxResult.success(data);
    }

    /**
     * 更新会员财务信息（App端专用）
     * 
     * @param updateRequest 更新请求参数
     * @return 更新结果，包含完整的用户信息
     */
    @PostMapping("/member/update-wallet")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateMemberWallet(@RequestBody UpdateWalletRequest updateRequest)
    {
        Long userId = SecurityUtils.getUserId();
        System.out.println("======== 开始更新会员财务信息 ========");
        System.out.println("用户ID: " + userId);
        System.out.println("更新类型: " + updateRequest.getType());
        System.out.println("金额: " + updateRequest.getAmount());
        
        // 查询现有会员信息
        RentalMemberInfo memberInfo = rentalMemberInfoService.selectRentalMemberInfoByUserId(userId);
        if (memberInfo == null)
        {
            System.out.println("错误: 会员信息不存在");
            return AjaxResult.error("会员信息不存在");
        }
        
        System.out.println("查询到的会员信息 - ID: " + memberInfo.getMemberId() + ", 当前钱包余额: " + memberInfo.getWalletBalance());
        
        // 验证更新类型和金额
        if (updateRequest.getAmount() == null || updateRequest.getAmount().compareTo(BigDecimal.ZERO) <= 0)
        {
            return AjaxResult.error("金额必须大于0");
        }
        
        // 根据更新类型处理
        switch (updateRequest.getType())
        {
            case "recharge":
                // 充值 - 增加钱包余额
                BigDecimal oldBalance = memberInfo.getWalletBalance();
                BigDecimal newWalletBalance = oldBalance.add(updateRequest.getAmount());
                memberInfo.setWalletBalance(newWalletBalance);
                System.out.println("充值操作 - 原余额: " + oldBalance + ", 新余额: " + newWalletBalance);
                
                // 更新总消费金额（充值不算消费，这里不更新totalAmount）
                if (memberInfo.getTotalAmount() == null) {
                    memberInfo.setTotalAmount(BigDecimal.ZERO);
                }
                break;
                
            case "consume":
                // 消费 - 减少钱包余额，增加总消费
                if (memberInfo.getWalletBalance().compareTo(updateRequest.getAmount()) < 0)
                {
                    return AjaxResult.error("钱包余额不足");
                }
                BigDecimal newWalletBalanceAfterConsume = memberInfo.getWalletBalance().subtract(updateRequest.getAmount());
                memberInfo.setWalletBalance(newWalletBalanceAfterConsume);
                
                // 更新总消费金额
                BigDecimal newTotalAmount = (memberInfo.getTotalAmount() != null) 
                    ? memberInfo.getTotalAmount().add(updateRequest.getAmount())
                    : updateRequest.getAmount();
                memberInfo.setTotalAmount(newTotalAmount);
                break;
                
            case "deposit":
                // 押金操作 - 更新押金余额
                if ("add".equals(updateRequest.getOperation())) {
                    // 增加押金
                    BigDecimal newDepositBalance = memberInfo.getDepositBalance().add(updateRequest.getAmount());
                    memberInfo.setDepositBalance(newDepositBalance);
                } else if ("subtract".equals(updateRequest.getOperation())) {
                    // 减少押金
                    if (memberInfo.getDepositBalance().compareTo(updateRequest.getAmount()) < 0)
                    {
                        return AjaxResult.error("押金余额不足");
                    }
                    BigDecimal newDepositBalance = memberInfo.getDepositBalance().subtract(updateRequest.getAmount());
                    memberInfo.setDepositBalance(newDepositBalance);
                } else {
                    return AjaxResult.error("押金操作类型无效");
                }
                break;
                
            default:
                return AjaxResult.error("更新类型无效");
        }
        
        // 设置更新时间
        memberInfo.setUpdatedTime(new java.util.Date());
        System.out.println("准备更新数据库 - 会员ID: " + memberInfo.getMemberId() + ", 新钱包余额: " + memberInfo.getWalletBalance());
        
        // 更新数据库
        int result = rentalMemberInfoService.updateRentalMemberInfo(memberInfo);
        System.out.println("数据库更新结果: " + (result > 0 ? "成功" : "失败") + ", 影响行数: " + result);
        
        if (result > 0)
        {
            // 重新查询最新的会员信息确认更新成功
            RentalMemberInfo updatedMemberInfo = rentalMemberInfoService.selectRentalMemberInfoByUserId(userId);
            System.out.println("重新查询的会员信息 - 钱包余额: " + updatedMemberInfo.getWalletBalance());
            
            // 同时获取用户信息，返回完整的用户资料
            SysUser originalUser = userService.selectUserById(userId);
            
            // 创建用户对象，只复制App端需要的字段
            SysUser user = new SysUser();
            user.setUserId(originalUser.getUserId());
            user.setUserName(originalUser.getUserName());
            user.setNickName(originalUser.getNickName());
            user.setEmail(originalUser.getEmail());
            user.setPhonenumber(originalUser.getPhonenumber());
            user.setSex(originalUser.getSex());
            user.setAvatar(originalUser.getAvatar());
            user.setStatus(originalUser.getStatus());
            user.setLoginIp(originalUser.getLoginIp());
            user.setLoginDate(originalUser.getLoginDate());
            user.setUserType(originalUser.getUserType());
            
            // 构建完整的响应数据，与获取用户资料接口保持一致
            java.util.Map<String, Object> data = new java.util.HashMap<>();
            data.put("user", user);
            data.put("memberInfo", updatedMemberInfo);
            
            System.out.println("======== 更新会员财务信息完成 ========");
            return AjaxResult.success("更新成功", data);
        }
        else
        {
            System.out.println("错误: 数据库更新失败");
            System.out.println("======== 更新会员财务信息失败 ========");
            return AjaxResult.error("更新失败");
        }
    }

    /**
     * 更新钱包请求参数
     */
    public static class UpdateWalletRequest
    {
        /** 更新类型：recharge-充值, consume-消费, deposit-押金 */
        private String type;
        
        /** 金额 */
        private BigDecimal amount;
        
        /** 操作类型（用于押金）：add-增加, subtract-减少 */
        private String operation;
        
        /** 备注说明 */
        private String remark;

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public BigDecimal getAmount() {
            return amount;
        }

        public void setAmount(BigDecimal amount) {
            this.amount = amount;
        }

        public String getOperation() {
            return operation;
        }

        public void setOperation(String operation) {
            this.operation = operation;
        }

        public String getRemark() {
            return remark;
        }

        public void setRemark(String remark) {
            this.remark = remark;
        }
    }
}